﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace Cordyceps.Micro.AuthServer.PostgresSql.DbMigrator.EFCore;

public class AuthMigrationsDbContextFactory : IDesignTimeDbContextFactory<AuthMigrationsDbContext>
{
    public AuthMigrationsDbContext CreateDbContext(string[] args)
    {
        // 构建配置。这里假设迁移器项目（最终运行工具的项目）的appsettings.json是配置源
        var configuration = BuildConfiguration();
        var connectionString = configuration.GetConnectionString("Default");
        // 配置DbContext选项
        var optionsBuilder = new DbContextOptionsBuilder<AuthMigrationsDbContext>()
            .UseNpgsql(
                configuration.GetConnectionString("Default"),
                options =>
                {
                    // ✅ 启用自动重试（对首次迁移特别有用）
                    options.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
                    // 显式指定迁移历史表位置
                    options.MigrationsHistoryTable("__EFMigrationsHistory", "public");
                });

        // .LogTo(Console.WriteLine, LogLevel.Information) // 调试时开启
        // .EnableSensitiveDataLogging());; // 根据你的数据库调整
        return new AuthMigrationsDbContext(optionsBuilder.Options);
    }

    private static IConfigurationRoot BuildConfiguration()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory()) // 指向迁移器项目的目录
            .AddJsonFile("appsettings.json", false)
            .AddJsonFile("appsettings.Development.json", true);

        return builder.Build();
    }
}